package com.ruoyi.project.video.task;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.project.video.domain.Video;
import com.ruoyi.project.video.service.IVideoService;
import com.ruoyi.project.video.utils.OkHttpUtils;
import com.ruoyi.project.video.utils.SSLSocketClient;
import com.ruoyi.project.video.utils.Url2Base64Utils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述: CrawlVideoTask
 * 创建时间: 2023/3/13 22:49
 * 作者: guozy
 * 版本: 1.0
 */
@Service
public class CrawlVideoTask {

    private String rootUrl = "https://99ifuk51.xyz/";
    private String IMAGE_URL = "https://3azpic.com";
    private String[] videoRootUrlList = new String[]{"https://922p2220.com", "https://922p2261.com", "https://922p2252.com", "https://922p2233.com", "https://922p2244.com", "https://922p2217.com"};
    private Random random = new Random();

    @Autowired
    private IVideoService videoService;

    /**
     * 描述: 定时视频爬虫
     * 版本: 1.0
     * 创建日期: 2023/3/13 23:37
     * 作者: guozy
     *
     * @param pageSize  页数
     * @param type      60：国产 110：日产
     * @return java.util.List<com.ruoyi.project.video.domain.Video>
     */
    public List<Video> reqVideoInfoList(Integer pageSize, String type) {
        List<Video> videoList = new CopyOnWriteArrayList<>();
        Executor executor = Executors.newFixedThreadPool(pageSize);
        CountDownLatch countDownLatch = new CountDownLatch(pageSize);
        try {
            for (int page = 0; page < pageSize; page++) {
                String url = String.format(rootUrl + "Html/%s/index-%s.html", type, page);
                // 正则表达式提取script链接
                Pattern pattern = Pattern.compile("(?<=\\()[^\\)]+");
                OkHttpClient client = OkHttpUtils.getInstance();
                Request.Builder builder = new Request.Builder();
                Request request = builder.url(url).addHeader("User-Agent", "/android/i").build();
                Response execute = client.newCall(request).execute();
                String html = execute.body().string();
                Document doc = Jsoup.parse(html);
                Elements videoElementList = doc.select("ul.tow1md > li.list1_obxobx > div.obxobxpd_md > div > a");
                for (Element element : videoElementList) {
                    Thread thread = new Thread(() -> {
                        try {
                            Video video = new Video();
                            video.setType(type);
                            // 跳转链接
                            String videoJumpUrl = element.select("a").attr("href");
                            // 图片链接
                            Matcher imageUrlMatcher = pattern.matcher(element.select("script").outerHtml());
                            if (imageUrlMatcher.find()) {
                                String imgUrl = IMAGE_URL + imageUrlMatcher.group().replace("\"", "");
                                try {
                                    video.setVideoImage(Url2Base64Utils.netSourceToBase64(client, builder, imgUrl));
                                } catch (IOException e) {
                                }
                            }
                            String title = element.select("p").text();
                            video.setId(UUID.randomUUID().toString().replace("-", ""));
                            video.setTitle(title);
                            // 播放路线源地址
                            Request videoSourceReq = builder.url(rootUrl + videoJumpUrl).build();
                            Response videoSourceRes = client.newCall(videoSourceReq).execute();
                            String videoSourceResHtml = videoSourceRes.body().string();
                            Document videoSourceHtmlDoc = Jsoup.parse(videoSourceResHtml);
                            // 视频地址
                            String videoDetailUrl = videoSourceHtmlDoc.select("div.film_bar > ul > li > a").first().attr("href");
                            Request videoDetailReq = builder.url(rootUrl + videoDetailUrl).build();
                            Response videoDetailRes = client.newCall(videoDetailReq).execute();
                            String videoDetailHtml = videoDetailRes.body().string();
                            Document videoDetailHtmlDoc = Jsoup.parse(videoDetailHtml);
                            Matcher videoUrlMatcher = pattern.matcher(videoDetailHtmlDoc.select("div.video-player > script").outerHtml());
                            if (videoUrlMatcher.find()) {
                                int randomInt = random.nextInt(6);
                                String videoRootUrl = videoRootUrlList[randomInt];
                                String videoUrl = videoRootUrl + videoUrlMatcher.group().replace("\"", "");
                                video.setVideoUrl(videoUrl);
                            }
                            video.setCrawlTime(new Date());
                            System.out.println(video);
                            videoList.add(video);
                            countDownLatch.countDown();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                    executor.execute(thread);
                }
            }
            videoService.insertVideoList(videoList);
            countDownLatch.await();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return videoList;
    }
}
